package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFetcherUtils;

/**
 * 爱彩票 开奖结果抓取
 * 
 * @author Sunshow
 * 
 */
public class LotteryDrawFetchWorkerAiCaiPiao extends AbstractLotteryDrawFetchWorker {

	private static final Map<LotteryType, String> lotteryTypeMap = new HashMap<LotteryType, String>();
	private static final Map<LotteryType, String> lotteryPhaseConvertionMap = new HashMap<LotteryType, String>();
	private static final Map<LotteryType, Object[]> phaseSearchDateMap = new HashMap<LotteryType, Object[]>();
	private static final Map<LotteryType, String> phaseLengthMap = new HashMap<LotteryType, String>();

	private static final String URL_DEFAULT = "http://kaijiang.aicai.com/open/kcResultByDate.do";

	static {
		lotteryTypeMap.put(LotteryType.SD11X5, "303");
		lotteryTypeMap.put(LotteryType.JX11X5, "304");
		lotteryTypeMap.put(LotteryType.JXSSC, "307");
		lotteryTypeMap.put(LotteryType.GD11X5, "305");
		lotteryTypeMap.put(LotteryType.JLK3, "308");
		lotteryTypeMap.put(LotteryType.CQSSC, "301");
		lotteryTypeMap.put(LotteryType.CQ11X5, "309");
		lotteryTypeMap.put(LotteryType.JSK3, "311");
        lotteryTypeMap.put(LotteryType.AHK3, "315");
		
		//lotteryTypeMap.put(LotteryType.SHSSL, "302");
		//lotteryTypeMap.put(LotteryType.GDKL10, "310");
		//lotteryTypeMap.put(LotteryType.SDQYH, "313");
		//lotteryTypeMap.put(LotteryType.GXKL10, "311");
		
		phaseSearchDateMap.put(LotteryType.SD11X5, new Object[]{"yyMMdd", 6});
		phaseSearchDateMap.put(LotteryType.JX11X5, new Object[]{"yyyyMMdd", 8});
		phaseSearchDateMap.put(LotteryType.JXSSC, new Object[]{"yyyyMMdd", 8});
		phaseSearchDateMap.put(LotteryType.GD11X5, new Object[]{"yyyyMMdd", 8});
		phaseSearchDateMap.put(LotteryType.JLK3, new Object[]{"yyyyMMdd", 8});
		phaseSearchDateMap.put(LotteryType.CQSSC, new Object[]{"yyyyMMdd", 8});
		phaseSearchDateMap.put(LotteryType.CQ11X5, new Object[]{"yyMMdd", 6});
		phaseSearchDateMap.put(LotteryType.JSK3, new Object[]{"yyyyMMdd", 8});
        phaseSearchDateMap.put(LotteryType.AHK3, new Object[]{"yyyyMMdd", 8});
		
		//phaseSearchDateMap.put(LotteryType.SD11X5, new Object[]{"yyyyMMdd", new Integer(8)});
		
		lotteryPhaseConvertionMap.put(LotteryType.GD11X5, "20");
		lotteryPhaseConvertionMap.put(LotteryType.JLK3, "20");
		lotteryPhaseConvertionMap.put(LotteryType.JSK3, "20");
        lotteryPhaseConvertionMap.put(LotteryType.AHK3, "20");
		
		phaseLengthMap.put(LotteryType.JLK3, "0");
		phaseLengthMap.put(LotteryType.JSK3, "0");
        phaseLengthMap.put(LotteryType.AHK3, "0");
	}

	public LotteryDrawFetchWorkerAiCaiPiao(LotteryType lotteryType) {
		super(lotteryType);
	}

	@Override
	public LotteryDraw fetchResult(String phase) {
		return this.fetchResultDetail(phase);
	}

	@Override
	public LotteryDraw fetchResultDetail(String phase) {
		LotteryType lotteryType = this.getLotteryType();

		if (StringUtils.isNotBlank(phase) && lotteryPhaseConvertionMap.containsKey(lotteryType)) {
			// 补回彩期
			phase = lotteryPhaseConvertionMap.get(lotteryType) + phase;
		}

		String fetchUrl = this.getResultDetailUrl(phase);
		if (StringUtils.isEmpty(fetchUrl)) {
			logger.error("==详细页面==抓取=={}==期号：{}==详细地址不存在，返回null", lotteryType.getName(), phase);
			return null;
		}
		fetchUrl += "?" + System.currentTimeMillis();
		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("Referer", "http://kaijiang.aicai.com/");
		headerParams.put("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");

        Map<String, String> requestParams = new HashMap<String, String>();

        String lotteryTypeExternal = lotteryTypeMap.get(lotteryType);
        String queryDateStr;
        if (StringUtils.isNotEmpty(phase)) {
            Object[] phaseSearchDateArray = phaseSearchDateMap.get(lotteryType);
            if (phaseSearchDateArray == null) {
                return null;
            }
            String dateStr = phaseSearchDateArray[0].toString();
            int dateLength = Integer.parseInt(phaseSearchDateArray[1].toString());
            try {
                queryDateStr = CoreDateUtils.formatDate(CoreDateUtils.parseDate(StringUtils.substring(phase, 0, dateLength), dateStr));
            } catch (Exception e) {
                logger.error("爱彩抓取开奖结果时根据传入彩期计算彩期时间有误。原因：{}", e.getMessage());
                return null;
            }
        } else {
            queryDateStr = CoreDateUtils.formatDate(new Date());
        }

        requestParams.put("gameIndex", lotteryTypeExternal);
        requestParams.put("searchDate", queryDateStr);

		String data = CoreFetcherUtils.URLPostWithHeaderParams(fetchUrl,
				headerParams, requestParams, CharsetConstant.CHARSET_UTF8);
		if (StringUtils.isEmpty(data)) {
			logger.error("data is null or 404 Not Found, url={}", fetchUrl);
			return null;
		}
		String resultHtml = "";
		try {
			JSONObject jsonObject = JSONObject.fromObject(data);
			resultHtml = jsonObject.getString("resultHtml");
		} catch (Exception e) {
			logger.error("转换抓取结果数据出错, data={}", data);
		}
		logger.info("data=" + resultHtml);

		try {
			String[] array = resultHtml.split("<tr[^>]*?>");
			Parser parser;
			NodeFilter filter = new TagNameFilter("td");
			for (String str : array) {
				if (StringUtils.isNotEmpty(str)) {
					parser = Parser.createParser(str, CharsetConstant.CHARSET_UTF8);
					NodeList nodeList = parser.extractAllNodesThatMatch(filter);
					String nodeStr = nodeList.elementAt(0).toPlainTextString();
					String tempPhase = nodeStr.replace("期", "").replace("-", "");
					//k3两边彩期中间差个0
					if (StringUtils.isNotEmpty(tempPhase) && phaseLengthMap.get(lotteryType) != null && tempPhase.length() == 10) {
						tempPhase = tempPhase.substring(0, 8) + phaseLengthMap.get(lotteryType) + tempPhase.substring(8, 10);
					}
					//如果传入彩期为空或者传入彩期与当前期相同
					if (StringUtils.isEmpty(phase) || tempPhase.equals(phase)) {
						LotteryDraw lotteryDraw = new LotteryDraw();
						String result = nodeList.elementAt(2).toPlainTextString();
						result = StringUtils.replace(result, "|", ",");
						String timeDraw = CoreDateUtils.formatDate(CoreDateUtils.parseDate(nodeList.elementAt(1).toPlainTextString(),"yyyy-MM-dd HH:mm"), CoreDateUtils.DATETIME);
						lotteryDraw.setLotteryType(lotteryType);
						lotteryDraw.setResult(result);
						lotteryDraw.setTimeDraw(timeDraw);
						lotteryDraw.setPhase(tempPhase);

                        if (lotteryPhaseConvertionMap.containsKey(lotteryType)) {
                            // 补回彩期
                            lotteryDraw.setPhase(StringUtils.substringAfter(lotteryDraw.getPhase(), lotteryPhaseConvertionMap.get(lotteryType)));
                        }

						return lotteryDraw;
					}
				}

			}
		} catch (Exception e) {
			logger.error("从抓取结果查找指定的开奖结果出错", e);
			return null;
		}
		return null;
	}

	@Override
	protected String getResultDetailUrl(String phase) {
		LotteryType lotteryType = this.getLotteryType();
		if (!lotteryTypeMap.containsKey(lotteryType)) {
			return null;
		}
		
		if (!phaseSearchDateMap.containsKey(lotteryType)) {
			return null;
		}

		return URL_DEFAULT;
	}

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}
}
